# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:
import requests
from lxml import etree
from copy import deepcopy
import random
import json
import logging
from citroen_sa_desc import citroen_sa_desc

class citroenLogin:

    def __init__(self):
        self.indexUrl = 'http://service.citroen.com/pages/index.jsp'
        self.indexUrl_CN = 'http://service.citroen.com/do/changerParametres'
        self.loginUrl = 'http://service.citroen.com/do/login'
        self.vinUrl = 'http://service.citroen.com/do/ok'
        self.carsInfoUrl = 'http://service.citroen.com/docapvAP/caracteristique.do'
        self.cookies = {}
        self.headers = {
            "Host": "service.citroen.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            # "": "",
        }
        self.map = {
            '东风标致206': 'VP01_VCO0009',
            '东风标致207': 'VP02_VCO0012',
            '208': 'VP01_VCO0014',
            '2008': 'VP01_VCO0016',
            '东风标致2008': 'VP02_VCO0017',
            '东风标致301': 'VP02_VCO0019',
            '东风标致307（T5）': 'VP01_VCO0022',
            '东风标致新307(T6)': 'VP02_VCO0023',
            '308': 'VP01_VCO0024',
            '东风标致308': 'VP02_VCO0025',
            '308(T9)': 'VP03_VCO0026',
            '东风标致308S': 'VP05_VCO0163',
            '东风标致新308': 'VP06_VCO0177',
            'RCZ': 'VP01_VCO0028',
            '3008': 'VP01_VCO0029',
            '东风标致3008': 'VP02_VCO0030',
            '407': 'VP01_VCO0036',
            '东风标致408': 'VP01_VCO0038',
            '东风标致新408': 'VP04_VCO0040',
            '4008': 'VP01_VCO0041',
            '4008东风标致(P84)': 'VP02_VCO0179',
            '东风标致508': 'VP02_VCO0043',
            '5008CHINE(P87)': 'VP03_VCO0182',
            '607': 'VP01_VCO0047',
            '607系列车型(改型)': 'VP02_VCO0048'
        }

    def updateCookies(self, cookies):
        for k in cookies:
            self.cookies[k] = cookies[k]

    def updateHeaders(self, headers):
        for k in headers:
            self.headers[k] = headers[k]

    def _get_cookies_str(self, cookies):
        cookieStr = ""
        for k, v in cookies.items():
            value = '%s=%s; ' % (k, v)
            cookieStr += value
        return cookieStr.strip('; ')

    def login(self):
        # 请求登录页
        try:
            response = requests.get(url=self.indexUrl, headers = self.headers, timeout=30, allow_redirects=False)
            index_html = etree.HTML(response.content.decode('utf8'))
            window_value = index_html.xpath('//input[@name="window"]/@value')[0]
            with open('./index.html', 'w') as i:
                i.write(response.content.decode('utf8'))
            cookies = response.cookies.get_dict()
            self.updateCookies(cookies)
            print(self.cookies)
            # 改为中文
            # 先增加cookies
            self.updateCookies({"Enabled": "true", "CodeLanguePaysOI": "zh_CN"})
            self.updateHeaders({"Referer": self.indexUrl})
            response = requests.get(url=self.indexUrl_CN, headers=self.headers, timeout=30, allow_redirects=False)
            self.updateCookies(response.cookies.get_dict())
            with open('./index_CN.html', 'w') as i:
                i.write(response.content.decode('utf8'))

            # 登录
            post_data = {
                "userid": "AN33983184",
                "password": "123456",
                "window": window_value,
            }
            response = requests.post(url=self.loginUrl, data=post_data, headers=self.headers, cookies=self.cookies, timeout=60)

            print(response.url)
            with open('./login.do.html', 'w') as i:
                i.write(response.content.decode('utf8'))
            self.updateCookies(response.cookies.get_dict())
            self.updateHeaders({"Referer": response.url})

            cookies_str = self._get_cookies_str(self.cookies)
            print(cookies_str)
            setData = {
                "cookies": cookies_str,
                "params": self.headers.get("Referer", "")
            }
            # logging.info("Login Success")
            return True, setData
        except:
            # logging.info("Login Fail")
            return False, {}

    def search(self, vin):
        post_data = {
            "VIN_OK_BUTTON.x": "{}".format(random.randint(5, 18)),
            "VIN_OK_BUTTON.y": "{}".format(random.randint(5, 18)),
            "jvin": vin,
            "wmi": vin[:3],
            "vds": vin[3:9],
            "vis": vin[9:],
        }

        post_data['jvin'] = vin
        # print(post_data)
        print(self.headers)
        print(self.cookies)
        # self.headers["Cookie"] = self._get_cookies_str(self.cookies)

        response = requests.post(url=self.vinUrl, data=post_data, headers=self.headers, cookies=self.cookies, timeout=30)
        with open('./vinRes.html', 'w') as i:
            i.write(response.content.decode('utf8'))
        self.updateCookies(response.cookies.get_dict())
        self.updateHeaders({"Referer": response.url})

        # 请求车辆信息页面
        response = requests.get(url=self.carsInfoUrl, headers = self.headers, cookies=self.cookies, timeout=60)
        with open('./carsInfo.html', 'w') as i:
            i.write(response.content.decode('utf8'))

        doc = etree.HTML(response.content.decode('utf8'))

        keys = doc.xpath('//div[@id="InfoZone"]/table[@class="table_lst_doc"]//td[@class="infoGenCar"]/text()')
        keys = [key.strip() for key in keys]
        attrs = doc.xpath(
            '//div[@id="InfoZone"]/table[@class="table_lst_doc"]//td[@class="infoCarText"]/text()')
        attrs = [attr.strip() for attr in attrs]
        zip_map = dict(zip(keys, attrs))
        # print(zip_map)

        name = zip_map.get(u'车系', '').strip()
        zu = zip_map.get(u'备件组号', '').strip()
        date = zip_map.get(u'保修起始日期', '').strip()
        psa = zip_map.get(u'P4A', '').strip()
        info_tab = doc.xpath('//div[@id="InfoZone"]/table[2]/tr[2]//tr')
        # infoVeh = info_tab.xpath('./tr[2]//tr')
        maindata = {}
        for tr in info_tab:
            key = tr.xpath('./td[1]/text()')[0].strip().replace('"', '').replace("'", '')
            val = tr.xpath('./td[2]/text()')[0].strip().replace('"', '').replace("'", '')
            maindata[key] = val
        # print(maindata)

        subdata = {}
        other_tabs = doc.xpath('//div[@id="InfoZone"]/table[position()>2]/tr[2]//tr')
        for tr in other_tabs:
            key = tr.xpath('./td[1]/text()')[0].strip().replace('"', '').replace("'", '')
            val = tr.xpath('./td[2]/text()')[0].strip().replace('"', '').replace("'", '')
            subdata[key] = val
        # print(subdata)

        side = subdata.get(u'侧循环', '')
        if u'侧循环' in subdata:
            del subdata[u'侧循环']
        val1 = list(maindata.values())
        val2 = list(subdata.values())
        val1.extend(val2)
        all_ = set(val1)
        extra = {
            'app_info': list(all_),
            'range': zu.strip(),
            'side': side,
            'psa': psa
        }
        extra = self.format_vin_ext(extra)
        vin_info = {}
        nme = name.replace(' ', '').strip()
        cid = self.map[nme]
        vin_info['code'] = cid.strip()
        vin_info['name'] = name.strip()
        vin_info['brandCode'] = 'peugeot'
        vin_info['createtime'] = 'now()'
        vin_info['shortVin'] = vin[-8:]
        vin_info['vin'] = vin
        vin_info['year'] = date.split('-')[0].strip()
        vin_info['maindata'] = json.dumps(
            maindata, ensure_ascii=False)
        vin_info['subdata'] = json.dumps(
            subdata, ensure_ascii=False)
        vin_info['extra_info'] = json.dumps(
            extra, ensure_ascii=False)
        # print(vin_info)
        rtn = {
            'vinInfo': vin_info,
            'code': 200
        }
        return True, rtn


    def format_vin_ext(self, extra_info):
        range = extra_info.get("range")
        OPR = range.split(" ")[0] if range.split(" ") else ""
        app_info = extra_info.get("app_info") if extra_info["app_info"] else []
        sa = self.get_sa(app_info)
        filter_rules = {"OPR": OPR, "sa": sa}
        extra_info["filter_rules"] = filter_rules
        return extra_info

    def get_sa(self, list):
        def new_i(i):
            try:
                if not isinstance(i, str):
                    i = i.encode('utf8')
                i = i.replace(" ", "").upper()
            except:
                pass
            return i
        _l = []
        for i in list:
            sa = citroen_sa_desc.get(new_i(i), "")
            if sa == "":
                continue
            _l.append(sa)
        return _l

    def run(self):
        try:
            self.login()
            # self.search('LDC973243G2528890')
        except Exception as e:
            print(e.__repr__())


if __name__ == '__main__':
    tools = citroenLogin()
    tools.run()